package com.jz.community.modulemine.packet.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jz.community.basecomm.base.BaseMvpFragment;
import com.jz.community.basecomm.glideConfig.GlideApp;
import com.jz.community.modulemine.R;
import com.jz.community.modulemine.R2;
import com.jz.community.modulemine.packet.bean.RedPacketBean;
import com.jz.community.modulemine.packet.presenter.RedPacketPresenter;
import com.jz.community.modulemine.packet.ui.RedPacketView;
import com.jz.community.modulemine.packet.ui.adapter.RedPacketAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class RedPacketFragment extends BaseMvpFragment<RedPacketView.View, RedPacketPresenter> implements RedPacketView.View, OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {


    @BindView(R2.id.red_packet_rv)
    RecyclerView redPacketRv;
    @BindView(R2.id.red_packet_refresh)
    SmartRefreshLayout redPacketRefresh;
    Unbinder unbinder;

    /**
     * 0 可使用 1 已失效
     */
    private int packetStatus;
    public static final String PACKET_STATUS = "com.jz.community.modulemine.packet.ui.fragment.PACKET_STATUS";

    private View noDataView;
    private View errorView;
    private View loadingView;

    private int page = 0;
    private int size = 10;
    private int totalPage = 0;

    private List<RedPacketBean.EmbeddedBean.RedPacketLogsBean> packetList = new ArrayList<>();
    private RedPacketAdapter adapterPacket;

    public static RedPacketFragment newInstance(int packetStatus) {
        RedPacketFragment packetFragment = new RedPacketFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(PACKET_STATUS, packetStatus);
        packetFragment.setArguments(bundle);
        return packetFragment;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.module_mine_fragment_red_packet;
    }

    @Override
    protected RedPacketPresenter createPresenter() {
        return new RedPacketPresenter(this);
    }

    @Override
    protected void initView() {
        super.initView();
    }

    @Override
    protected void initLazy(@Nullable Bundle savedInstanceState) {
        super.initLazy(savedInstanceState);
        Bundle bundle = getArguments();
        packetStatus = bundle.getInt(PACKET_STATUS);
        initRecyclerView();
    }

    private void initRecyclerView() {
        noDataView = getActivity().getLayoutInflater().inflate(R.layout.view_empty, (ViewGroup) redPacketRv.getParent(), false);

        ImageView emptyIv = (ImageView) noDataView.findViewById(R.id.empty_img);
        TextView emptyTv = (TextView) noDataView.findViewById(R.id.empty_tv);

        emptyIv.setImageResource(R.mipmap.empty_default);
        emptyTv.setText("暂无红包！");

        errorView = getActivity().getLayoutInflater().inflate(R.layout.view_error, (ViewGroup) redPacketRv.getParent(), false);

        ImageView errorIv = (ImageView) errorView.findViewById(R.id.error_img);
        errorIv.setImageResource(R.mipmap.error_default);

        loadingView = getActivity().getLayoutInflater().inflate(R.layout.view_loading, (ViewGroup) redPacketRv.getParent(), false);
        ImageView loadingIv = (ImageView) loadingView.findViewById(R.id.loading_img);
        GlideApp.with(getActivity())
                .asGif()
                .load(R.drawable.loading_default)
                .into(loadingIv);

        //init-packet-recyclerView
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        redPacketRv.setHasFixedSize(true);
        redPacketRv.setFocusable(false);
        redPacketRv.setLayoutManager(layoutManager);
        redPacketRefresh.setEnableLoadMore(false);
        redPacketRefresh.setOnRefreshListener(this);

        adapterPacket = new RedPacketAdapter(R.layout.module_mine_item_red_packet, packetList, packetStatus);
        adapterPacket.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        adapterPacket.setOnLoadMoreListener(this, redPacketRv);
        redPacketRv.setAdapter(adapterPacket);

        errorView.setOnClickListener(v -> {
            page = 0;
            adapterPacket.setEmptyView(loadingView);
            mPresenter.initPacketData(packetStatus, page, size);
        });

        adapterPacket.setEmptyView(loadingView);
        mPresenter.initPacketData(packetStatus, page, size);
    }

    @Override
    public void showRedPacket(RedPacketBean entity) {
        freshEnd();
        //总页数
        totalPage = entity.getPage().getTotalPages();

        if (totalPage <= 0) {
            //先设置空布局
            if (page == 0) {
                adapterPacket.replaceData(new ArrayList<>());
                adapterPacket.setEmptyView(noDataView);
                adapterPacket.notifyDataSetChanged();
            } else {
                adapterPacket.setEmptyView(noDataView);
                adapterPacket.notifyDataSetChanged();
            }
        } else {
            packetList = entity.get_embedded().getRedPacketLogs();
            if (page == 0) {
                adapterPacket.setNewData(packetList);
                //如果数据少 不显示已加载全部
                adapterPacket.disableLoadMoreIfNotFullPage();
            } else {
                adapterPacket.addData(packetList);

            }
        }

        adapterPacket.loadMoreComplete();

    }

    @Override
    public void showError(String msg) {
        freshEnd();
        if (null != adapterPacket) {
            adapterPacket.setEmptyView(errorView);
            adapterPacket.loadMoreFail();
        }

    }

    private void freshEnd() {
        redPacketRefresh.finishRefresh(200);
    }

    @Override
    public void onRefresh(RefreshLayout refreshLayout) {
        if (null != adapterPacket) {
            adapterPacket.setEnableLoadMore(false);
            adapterPacket.replaceData(new ArrayList<>());
            adapterPacket.setEmptyView(loadingView);
        }
        page = 0;
        mPresenter.initPacketData(packetStatus, page, size);
        adapterPacket.setEnableLoadMore(true);

    }

    @Override
    public void onLoadMoreRequested() {
        redPacketRefresh.setEnableRefresh(false);
        if (totalPage > 0) {
            if (page < totalPage - 1) {
                page++;
                mPresenter.initPacketData(packetStatus, page, size);
                redPacketRefresh.setEnableRefresh(true);
            } else {
                adapterPacket.loadMoreEnd();
                redPacketRefresh.setEnableRefresh(true);
            }
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
